package com.alibaba.cloud.utils;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;

/**
 * @Description:校验工具类
 * @author: zhb1316783262@163.com
 * @date: 2019年2月21日下午2:10:14
 */
public class ValidatorUtil {
	/**
	 * 开启快速结束模式 failFast (true)
	 */
	private static Validator failFastValidator = Validation.byProvider(HibernateValidator.class).configure()
			.messageInterpolator(new ParameterMessageInterpolator()).failFast(true).buildValidatorFactory()
			.getValidator();

	/**
	 * 全部校验
	 */
	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	/**
	 * 注解验证参数(快速失败模式)
	 *
	 * @param obj
	 */
	public static <T> Boolean fastFailValidate(T obj) {
		Set<ConstraintViolation<T>> constraintViolations = failFastValidator.validate(obj);
		// 返回异常result
		if (!constraintViolations.isEmpty()) {
			return ValidResult.fail(constraintViolations.iterator().next().getPropertyPath().toString(),
					constraintViolations.iterator().next().getMessage());
		}
		return true;
	}

	/**
	 * 注解验证参数(全部校验)
	 *
	 * @param obj
	 */
	public static <T> Boolean allCheckValidate(T obj) {
		Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
		// 返回异常result
		if (!constraintViolations.isEmpty()) {
			List<String> errorMessages = new LinkedList<>();
			Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
			while (iterator.hasNext()) {
				ConstraintViolation<T> violation = iterator.next();
				errorMessages
						.add(String.format("%s:%s", violation.getPropertyPath().toString(), violation.getMessage()));
			}
			return ValidResult.fail(errorMessages);
		}
		return true;
	}

}
